﻿$(function () {
    layui.use(['notice', 'layer', 'table', 'iziToast', 'util', 'laypage', 'numberInput'], function () {
        var layer = layui.layer,
            table = layui.table,
            notice = Util.notice !== null && Util.notice() !== null
                ? Util.notice() : layui.notice,
            iziToast = layui.iziToast,
            util = layui.util,
            laypage = layui.laypage,
            numberInput = layui.numberInput;
        var lodash = _,
            tableIns = null,
            numInputIns = null,
            //监听表格数据行按钮
            editurl = "/business/newsmanage/edit",
            editWidowConfig = {
                title: "编辑/修改",
                type: 2,
                content: "",
                fixtolayoutbody: true,
                anim: 3,
                end: function () {
                    tableIns.reload(newslisttableconfig);
                }
            },
            currentSystemModuleId = $("#currentSystemModuleId").val();

        var EditNews = function (btnid, newsid, iscopy) {
            editWidowConfig.content = editurl + "?moduleid=" + currentSystemModuleId + "&buttonid=" + btnid + "&newsid=" + newsid;
            if (!lodash.isNil(iscopy))
                editWidowConfig.content += "&copy=true";
            Util.OpenMainWindow(editWidowConfig);
        };
        var DeleteNews = function (newsid, btnid, moduleid, tableRow) {
            layer.confirm("确定要进行删除操作吗？", function (confirmIndex) {
                layer.close(confirmIndex);
                iziToast.loading("删除中，请稍候...");
                let node = new Object(DeleteNodeModel);
                node.EntityId = newsid;
                node.ButtonId = btnid;
                node.ModuleId = moduleid;
                $.deleteJSON("/api/backend/business/newsmanage/delete", node, function (res) {
                    iziToast.destroy();
                    if (!httpapi.checkResponse(res)) {
                        //输入信息校验错误
                        notice.error(res.message);
                    } else {//Success
                        notice.success(res.message);
                        if (!lodash.isNil(tableRow))
                            tableRow.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    }
                });
            });
        };
        //url: int Id of newsItemId
        //datas: object for api parameters 
        //callback: function
        var updateTableRow = function (url, datas, callback) {
            if (!lodash.isObject(datas) && !lodash.isEmpty(datas))
                return false;
            var index = layer.load(2, { time: 10 * 1000 });
            httpapi.fetchGet(url, datas).then(res => {
                layer.close(index);
                if (!httpapi.checkResponse(res)) {
                    //输入信息校验错误
                    notice.error(res.message);
                }
                else {//Success
                    if (lodash.isFunction(callback)) {
                        callback(res.message, res.data);
                    }
                }
            }).catch(error => consol.error(error));
        };

        table.on('tool(newslisttable)', function (obj) {
            var data = obj.data,
                thisElem = this,
                buttonid = layui.$(thisElem).data("buttonid");
            if (obj.event === 'Edit') {
                EditNews(buttonid, data.Id);
            } else if (obj.event === 'Copy') {
                EditNews(buttonid, data.Id, true);
            }
            else if (obj.event === 'Delete') {
                DeleteNews(data.Id, buttonid, currentSystemModuleId, obj);
            }
            else if (obj.event === 'setRecommend') {
                updateTableRow('/api/backend/business/newsmanage/setrecommend', { newsid: data.Id }, function (msg, newdata) {
                    //同步更新表格和缓存对应的值
                    obj.update({
                        IsRecommend: newdata//res.data
                    });
                });
            }
            else if (obj.event === 'setDisplayOrder') {
                layer.open({
                    type: 1
                    , title: '设置排序'
                    , content: document.getElementById("displayorderInputTpl").innerHTML
                    , resize: false
                    , success: function (layero, index) {
                        var options = {
                            step: 1,
                            min: 1,
                            max: 150
                        };
                        if (numInputIns === null)
                            numInputIns = numberInput.render(options);
                        else numInputIns.reload(options);

                        numInputIns.setInitNumber(data.DisplayOrder);
                    }
                    , btn: ['确定']
                    , yes: function (index, layero) {
                        var newsetVal = numInputIns.getCurrentNumber();
                        if (Util.isNumber(newsetVal)) {
                            updateTableRow('/api/backend/business/newsmanage/setorder', { newsid: data.Id, order: newsetVal }, function (msg, neworder) {
                                if (msg.length > 0)
                                    notice.success(msg);
                                obj.update({
                                    DisplayOrder: neworder//res.data
                                });
                            });
                        } else {
                            notice.error("请输入正确数值");
                            if (tableIns !== null)
                                tableIns.reload(newslisttableconfig);
                        }
                        layer.close(index);
                    }
                });
            }
        });
        //监听单元格编辑
        //table.on('edit(newslisttable)', function (obj) {
        //    var value = obj.value //得到修改后的值
        //        , data = obj.data //得到所在行所有键值
        //        , field = obj.field; //得到字段
        //    if (field === "DisplayOrder") {
        //        if (value.trim() !== "" && Util.isNumber(value.trim())) {
        //            updateTableRow('/api/backend/business/newsmanage/setorder', { newsid: data.Id, order: value }, function (msg, data) {
        //                if (tableIns !== null)
        //                    tableIns.reload(newslisttableconfig);
        //            });
        //        } else {
        //            notice.error("请输入正确数值");
        //            if (tableIns !== null)
        //                tableIns.reload(newslisttableconfig);
        //        }
        //    }
        //});
        //-----常规文章表格显示-----

        //DavidLee 2020/05/15 整合博客管理界面
        //For ant design vue: menu
        var SubMenu = {
            template: `
              <a-sub-menu :key="menuInfo.id" v-bind="$props" v-on="$listeners">
                <span slot="title">
                  <i class="layui-icon layui-icon-triangle-r"></i><span>{{ menuInfo.title }}<span class="layui-badge layui-bg-gray" style="margin-left: 5px;" v-if="menuInfo.children.length > 0">{{menuInfo.children.length}}</span></span>
                </span>
                <template v-for="item in menuInfo.children">
                  <a-menu-item v-if="item.children.length == 0" :key="item.id">
                    <span>{{ item.title }}</span>
                  </a-menu-item>
                  <sub-menu v-else :key="item.id" :menu-info="item" />
                </template>
              </a-sub-menu>
            `,
            name: 'SubMenu',
            // must add isSubMenu: true
            isSubMenu: true,
            //props: {
            //    ...antd.Menu.SubMenu.props,
            //    // Cannot overlap with properties within Menu.SubMenu.props
            //    menuInfo: {
            //        type: Object,
            //        default: () => ({}),
            //    },
            //},
            props: lodash.assignIn({ //For Microsoft edge Compatiable
                menuInfo: {
                    type: Object,
                    default: {}
                }
            }, antd.Menu.SubMenu.props),
            components: {
                'SubMenu': SubMenu,
                'ASubMenu': antd.Menu.SubMenu,
                'AMenuItem': antd.Menu.Item
            },
        };
        var vm = new Vue({
            el: '#newsmanage',
            components: {
                'SubMenu': SubMenu,
                'AMenu': antd.Menu,
                'AMenuItem': antd.Menu.Item,
                'ASpin': antd.Spin
            },
            data: {
                //文章检索显示
                displaysearchpanel: false,
                pager: null,
                keywords: "",
                newsdata: [],
                elapsed: 0,
                total: 0,
                pagesize: newslisttableconfig.limit,
                page: 1,
                searchUrl: "/api/backend/business/newsmanage/search",
                //栏目菜单导航栏
                columntype: $("#columntreeType").val(),
                loadingmenus: true,
                delayTime: 200,
                menuItems: [],
                currentColumnId: 0
            },
            mounted: function () {
                tableIns = table.render(newslisttableconfig);
                this.onLoadNavMenus();
            },
            methods: {
                //文章检索方法
                searchNews: function () {
                    if (this.keywords.trim() !== "") {
                        this.LoadSearchNewsList(this.page, this.pagesize);
                    }
                },
                LoadSearchNewsList: function (page, pagesize) {
                    var _this = this,
                        loading = layer.load(2, { time: 10 * 1000 });
                    httpapi.fetchGet(_this.searchUrl + "?s=" + _this.keywords + "&page=" + page + "&pagesize=" + pagesize).then(res => {
                        layer.close(loading);
                        if (!httpapi.checkResponse(res))
                            //输入信息校验错误
                            iziToast.error({
                                title: '消息通知',
                                message: res.message
                            });
                        else {
                            if (!$("#newstablepanel").hasClass("layui-hide")) {
                                $("#newstablepanel").addClass("layui-hide");
                            }
                            _this.newsdata = res.data.Results;
                            _this.elapsed = res.data.Elapsed;
                            _this.total = res.data.Total;
                            if (_this.pager === null) {
                                _this.pager = laypage.render({
                                    elem: 'pageContainer'
                                    , count: res.data.Total
                                    , layout: ['count', 'prev', 'page', 'next']
                                    , theme: '#1E9FFF'
                                    , limit: pagesize
                                    , jump: function (obj, first) {
                                        //首次不执行
                                        if (!first)
                                            _this.LoadSearchNewsList(obj.curr, obj.limit);
                                    }
                                });
                            }
                        }
                    }).catch(error => console.error(error));
                },
                ReloadPage: function (isreloadtable) {
                    var _this = this;
                    $("#searchpanel").removeClass("layui-anim layui-anim-up");
                    $("#newstablepanel").removeClass("layui-anim layui-anim-fadeout layui-hide");
                    _this.displaysearchpanel = false;
                    _this.newsdata = [];
                    _this.keywords = "";
                    _this.pager = null;
                    if (!lodash.isNil(isreloadtable) && isreloadtable)
                        tableIns.reload(newslisttableconfig);
                },
                ItemClick: function (btnId, eventName, item) {
                    var _this = this;
                    if (eventName === 'Edit') {
                        _this.ReloadPage(false);
                        EditNews(btnId, item.Id);
                    } else if (eventName === 'Copy') {
                        _this.ReloadPage(false);
                        EditNews(btnId, item.Id, true);
                    } else if (eventName === 'Delete') {
                        DeleteNews(item.Id, btnId, currentSystemModuleId);
                        let itemIndex = lodash.findIndex(_this.newsdata, ['Id', item.Id]);
                        if (itemIndex >= 0)
                            _this.newsdata.splice(itemIndex, 1);
                    }
                },
                //导航栏菜单方法
                onLoadNavMenus: function () {
                    const apiUrl = '/api/backend/business/columnmanage/getauthcolumntree?columntype=' + this.columntype;
                    const me = this;
                    me.loadingmenus = true;
                    httpapi.fetchGet(apiUrl).then(res => {
                        if (!httpapi.checkResponse(res))
                            //输入信息校验错误
                            notice.error(res.message);
                        else {//Success
                            me.loadingmenus = false;
                            me.menuItems = res.data;
                        }
                    }).catch(error => {
                        notice.error("对不起，出现未知错误，请您联系系统管理员！");
                        console.error(error);
                    });
                },
                onSelectMenuItem: function (item) {
                    //console.log('click ', item);
                    if (newslisttableconfig.url.indexOf('?') >= 0) {
                        let arr_url = newslisttableconfig.url.split('?');
                        newslisttableconfig.url = arr_url[0];
                    }
                    newslisttableconfig.url += '?isauth=true&cid=' + item.key;
                    newslisttableconfig.page.curr = 1;
                    tableIns.reload(newslisttableconfig);
                    //DavidLee 2020/08/17 增加点击对应栏目时点击添加文章在文章编辑页面栏目树自动选择对应栏目
                    this.currentColumnId = item.key;
                },
                //utilities
                formatTime: function (time) {
                    return util.toDateString(time, "yyyy-MM-dd HH:mm:ss");
                }
            }
        });

        //搜索文章响应
        $("#searchNewsBtn").on("click", function () {
            var $keywords = $("input[name=newsSearch]");
            if ($keywords.val() !== "") {
                $("#newstablepanel").addClass("layui-anim layui-anim-fadeout");
                vm.displaysearchpanel = true;
                $("#searchpanel").addClass("layui-anim layui-anim-up");
                vm.keywords = $keywords.val();
                vm.searchNews();
            }
        });

        //监听顶部按钮栏
        var PageButtonEvent = {
            Add: function (buttonid) {
                editWidowConfig.content = editurl + "?moduleid=" + currentSystemModuleId + "&buttonid=" + buttonid;
                if (vm.currentColumnId > 0)
                    editWidowConfig.content += "&columnid=" + vm.currentColumnId;
                Util.OpenMainWindow(editWidowConfig);
                if (vm.displayType !== "table")
                    vm.ReloadPage(false);
                return false;
            }
        };
        $('.pagebuttongroup .layui-btn').on('click', function (e) {
            e.preventDefault();
            var type = $(this).data('type');
            var buttonid = $(this).data("buttonid");
            PageButtonEvent[type] ? PageButtonEvent[type].call(this, buttonid) : '';
        });

    });//layui.use([
}); //$(function () {